package org.stvd.repository.admin.impl;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.stvd.core.dto.QueryResult;
import org.stvd.entities.admin.Users;
import org.stvd.repository.admin.UsersDao;
import org.stvd.repository.base.impl.BaseDaoImpl;

@Repository("UsersDao")
public class UsersDaoImpl extends BaseDaoImpl<Users> implements UsersDao {

    @Override
    public List<Users> findUsers(String userId, String depId, String depType, String guid) {
        String hql = "select T1 from Users T1 where (T1.userId = ?0 or '' = ?0) "
                + " and exists(select T2.depId from UserDep T2,Department T3 where T2.depId=T3.depId "
                + " and T2.userId=T1.userId and ('' = ?1 or T3.depId = ?1)"
                + " and ('' = ?2 or T3.depType= ?2) and T3.guid = ?3) ";
        return this.findByHQL(hql, userId, depId, depType, guid);
    }

    @Override
    public QueryResult<Users> getUsersQueryResult(int start, int limit, String loginAccount, String userName,
        List<String> depIds, String roleId, String guid) {
        String hql = "SELECT T1 FROM Users T1 WHERE T1.uname LIKE ?1"
                + " AND EXISTS ("
                    + " SELECT T2.depId FROM UserDep T2, Department T3 WHERE T2.depId=T3.depId"
                    + " AND T2.userId = T1.userId AND T3.depId IN (?2) and T2.guid = ?4"
                + " ) AND (?3 = '' OR EXISTS ("
                    + " SELECT T4.userId FROM UserRole T4, Roles T5 WHERE T4.roleId = T5.roleId"
                    + " AND T4.userId = T1.userId AND T5.roleId = ?3 AND T4.guid = ?4)"
                + " ) AND EXISTS ("
                    + " SELECT T6.id FROM UserLogin T6 WHERE T6.loginAccount LIKE ?0 AND T6.userId = T1.userId"
                + " ) ORDER BY T1.modifyDate DESC ";
        return getQueryResultByHQL(start, limit, hql, "%"+loginAccount+"%", "%" + userName + "%", depIds, roleId, guid);
    }

}
